<template>
  <div class="app-container">
    <!-- 筛选 -->
    <el-card>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>

        <el-form-item label="原料号">
          <el-input
            v-model="queryParams.materialNo"
            placeholder="请输入原料号"
            clearable
            @keydown.enter.prevent="handleQuery"
          />
        </el-form-item>

        <el-form-item label="品名">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入品名"
            clearable
            @keydown.enter.prevent="handleQuery"
          />
        </el-form-item>

        <el-form-item label="许可证号">
          <el-select
            v-model="queryParams.licenseNo"
            placeholder="请选择许可证号"
            clearable
            filterable
          >
            <el-option
              v-for="item in licenseOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格与新增按钮 -->
    <el-card class="mt20">
      <el-row justify="space-between" class="mb10">
        <span style="font-size: 18px">投料记录</span>
        <el-button type="primary" icon="Plus" @click="handleAdd"
          >新增记录</el-button
        >
      </el-row>

      <el-table :data="recordList" border stripe v-loading="loading">
        <el-table-column prop="licenseNo" label="许可证号" />
        <el-table-column prop="customsNo" label="报关单号" />
        <el-table-column prop="transferNo" label="调运单号" />
        <el-table-column prop="materialNo" label="原料料号" />
        <el-table-column prop="contractNo" label="成品料号" />
        <el-table-column prop="productName" label="品名" />
        <el-table-column prop="infeedNum" label="投料数量（吨）" />
        <el-table-column prop="scrapsNum" label="下脚料数量（kg）" />
        <el-table-column prop="highTmpNum" label="高温数量（吨）" />
        <el-table-column prop="crushingNum" label="破碎数量（吨）" />
        <el-table-column prop="packageNum" label="包数（包）" />
        <el-table-column prop="finishedProductNum" label="成品数量（吨）" />
        <el-table-column prop="curChargePerson" label="负责人" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewDetail(row)"
              >编辑</el-button
            >
            <el-button
              v-hasPermi="['bomList:all:delete']"
              link
              type="danger"
              @click="deleteRow(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 弹窗表单 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id ? '编辑记录' : '新增记录'"
      width="600px"
    >
      <el-form :model="formData" label-width="140px">
        <el-form-item label="许可证号">
          <el-select
            v-model="formData.licenseNo"
            placeholder="请选择许可证号"
            filterable
          >
            <el-option
              v-for="item in licenseOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报关单号">
          <el-select
            v-model="formData.customsNo"
            placeholder="请选择报关单号"
            filterable
          >
            <el-option
              v-for="item in customsOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调运单号">
          <el-input v-model="formData.transferNo" />
        </el-form-item>
        <el-form-item label="原料料号">
          <el-input v-model="formData.materialNo" />
        </el-form-item>
        <el-form-item label="成品料号">
          <el-input v-model="formData.contractNo" />
        </el-form-item>
        <el-form-item label="品名">
          <el-input v-model="formData.productName" />
        </el-form-item>
        <el-form-item label="成品数量（吨）">
          <el-input-number
            v-model="formData.finishedProductNum"
            :min="0"
            @change="recalculate"
          />
        </el-form-item>
        <el-form-item label="单包重量（KG）">
          <el-input-number
            v-model="formData.singlePackageWeight"
            :min="0"
            @change="recalculate"
          />
        </el-form-item>
        <el-form-item label="包数（包）">
          <el-input-number v-model="formData.packageNum" :disabled="true" />
        </el-form-item>
        <el-form-item label="破碎数量（吨）">
          <el-input-number v-model="formData.crushingNum" :disabled="true" />
        </el-form-item>
        <el-form-item label="袋皮重量（吨）">
          <el-input-number v-model="formData.bagWeight" :disabled="true" />
        </el-form-item>
        <el-form-item label="高温数量（吨）">
          <el-input-number v-model="formData.highTmpNum" :disabled="true" />
        </el-form-item>
        <el-form-item label="下脚料数量（KG）">
          <el-input-number v-model="formData.scrapsNum" :disabled="true" />
        </el-form-item>
        <el-form-item label="原料投料数量（吨）">
          <el-input-number v-model="formData.infeedNum" :disabled="true" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="formData.curChargePerson" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  bom_list as listProduce,
  bom_add as addProduce,
  bom_edit as updateProduce,
  bom_delete as delProduce,
} from "@/api/wms/bomList";

import { queryLicenseList, queryCustomsNoList } from "@/api/wms/whole";

// 日期范围
const dateRange = ref([]); // [start, end]

// 加载状态和分页
const loading = ref(false);
const total = ref(0);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  licenseNo: "",
  productName: "",
  materialNo: "",
  createStartTime: "",
  createEndTime: "",
});

// 数据列表
const recordList = ref([]);
const dialogVisible = ref(false);

// 下拉选项
const licenseOptions = ref([]);
const customsOptions = ref([]);

// 表单数据
const formData = reactive({
  id: null,
  licenseNo: "",
  customsNo: "",
  contractNo: "",
  infeedNum: 0,
  scrapsNum: 0,
  highTmpNum: 0,
  crushingNum: 0,
  packageNum: 0,
  finishedProductNum: 0,
  curChargePerson: "",
  materialNo: "", // 原料号，字符串
  productName: "", // 品名，字符串
  transferNo: "", // 调运单号，字符串
  singlePackageWeight: 0, // 单包重量，数字（单位KG）
  bagWeight: 0, // 袋皮重量，数字（单位KG）
});

// 方法区域
function resetForm() {
  Object.assign(formData, {
    id: null,
    licenseNo: "",
    customsNo: "",
    contractNo: "",
    infeedNum: 0,
    scrapsNum: 0,
    highTmpNum: 0,
    crushingNum: 0,
    packageNum: 0,
    finishedProductNum: 0,
    curChargePerson: "",
    materialNo: "", // 原料号，字符串
    productName: "", // 品名，字符串
    transferNo: "", // 调运单号，字符串
    singlePackageWeight: 0, // 单包重量，数字（单位KG）
    bagWeight: 0, // 袋皮重量，数字（单位KG）
  });
}

function handleAdd() {
  resetForm();
  dialogVisible.value = true;
}

function recalculate() {
  // 成品数量（吨）
  const finishedProductNum = Number(formData.finishedProductNum);
  // 单包重量（KG）
  const singlePackageWeight = Number(formData.singlePackageWeight);
  // 包数量
  const packageNum = (
    (finishedProductNum * 1000) /
    singlePackageWeight
  ).toFixed(0); // 包
  // 皮袋
  const bagWeight = ((packageNum * 0.06) / 1000).toFixed(3);
  // 破碎
  const crushed = finishedProductNum - bagWeight;
  // 高温
  const highTemp = crushed;
  // 下脚料
  const scrapKg = highTemp * 0.0004 * 1000;
  // 原料
  const infeedNum = (highTemp + scrapKg / 1000).toFixed(3);

  formData.packageNum = packageNum;
  formData.bagWeight = bagWeight;
  formData.highTmpNum = highTemp;
  formData.crushingNum = crushed;
  formData.scrapsNum = scrapKg.toFixed(3);
  formData.infeedNum = infeedNum;
}

function viewDetail(row) {
  Object.assign(formData, { ...row });
  dialogVisible.value = true;
}

async function handleQuery() {
  if (dateRange.value && dateRange.value.length) {
    queryParams.createStartTime = dateRange.value[0];
    queryParams.createEndTime = dateRange.value[1];
    console.log(queryParams, "queryParams");
  } else {
    queryParams.createStartTime = "";
    queryParams.createEndTime = "";
  }
  loading.value = true;
  try {
    const res = await listProduce(queryParams);
    res.rows.forEach((element) => {
      element.infeedNum = (element.infeedNum / 1).toFixed(3);
      element.scrapsNum = (element.scrapsNum / 1).toFixed(0);
      element.highTmpNum = (element.highTmpNum / 1).toFixed(3);
      element.crushingNum = (element.crushingNum / 1).toFixed(3);
      element.finishedProductNum = (element.finishedProductNum / 1).toFixed(3);
    });
    recordList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (err) {
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
}

function resetQuery() {
  queryParams.pageNum = 1;
  queryParams.licenseNo = "";
  queryParams.materialNo = "";
  queryParams.productName = "";
  queryParams.createStartTime = "";
  queryParams.createEndTime = "";
  dateRange.value = [];
  handleQuery();
}

async function submitForm() {
  try {
    if (formData.id) {
      await updateProduce(formData);
      ElMessage.success("更新成功");
    } else {
      await addProduce(formData);
      ElMessage.success("新增成功");
    }
    dialogVisible.value = false;
    handleQuery();
  } catch (err) {
    ElMessage.error("提交失败");
  }
}

function deleteRow(row) {
  ElMessageBox.confirm("确定要删除此记录吗？", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await delProduce(row.id);
      ElMessage.success("删除成功");
      handleQuery();
    } catch (err) {
      ElMessage.error("删除失败");
    }
  });
}

async function loadSelectOptions() {
  try {
    const [licenseRes, customsRes] = await Promise.all([
      queryLicenseList(),
      queryCustomsNoList(),
    ]);

    licenseOptions.value = (licenseRes.data || []).map((item) => {
      const num = parseFloat(item);
      return isNaN(num) ? item : Math.floor(num);
    });

    customsOptions.value = customsRes.data.filter((pre) => pre) || [];
  } catch (e) {
    ElMessage.error("加载下拉选项失败");
  }
}

// 初始化
onMounted(() => {
  handleQuery();
  loadSelectOptions();
});
</script>

<style scoped>
.mt20 {
  margin-top: 20px;
}
.mb10 {
  margin-bottom: 10px;
}
.pagination-wrapper {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
